package com.jixiantubu.wode;

import image.SmartImageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import view.Circleimage;
import com.example.jixiantubu.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jixiantubu.bean.UserBean;
import com.jixiantubu.util.MyApplication;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Wo_ziliaoActivity extends Activity /* implements OnClickListener */{
	SmartImageView wo_photo;
	Intent intent;
	Byte[] data;
	String string;
	Bitmap bitmap;
	Uri uri;
	 Dialog dialog;
	private String filename = "xiaochun" + System.currentTimeMillis() + ".jpg";
	private ProgressDialog myDialog;
	EditText wo_jianjie, editText2, editText3;
	String nicheng, xingbie, jianjie;
	MyApplication application;
	// 数据来源
	List<UserBean> list = new ArrayList<UserBean>();
	// ZiliaoAdapter adapter;
	HttpUtils httpUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = this.getWindow();
		window.requestFeature(window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_wo_ziliao);
		initView();
		initData();
	}

	private void initView() {
		wo_photo = (SmartImageView) findViewById(R.id.wo_photo);
		wo_photo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog();
			}
		});
		editText2 = (EditText) findViewById(R.id.editText2);// 昵称
		editText3 = (EditText) findViewById(R.id.editText3);// 性别
		wo_jianjie = (EditText) findViewById(R.id.wo_jianjie);// 简介
	}
	public void sure(View view) {
		nicheng = editText2.getText().toString().trim();
		xingbie = editText3.getText().toString().trim();
		jianjie = wo_jianjie.getText().toString().trim();

		// 使用AsynHttpClient框架通过get请求上传昵称，性别，和简介
		AsyncHttpClient client = new AsyncHttpClient();
		String url = "http://" + MyApplication.getIP()
				+ ":8080/Jinnang/WoGuanzhu";
		final com.loopj.android.http.RequestParams as = new com.loopj.android.http.RequestParams();
		// as.put("asdf","123");
		
		as.put("key", 3);
		as.put("username", application.username);
		as.put("nicheng", nicheng);
		as.put("sex", xingbie);
		as.put("jianjie", jianjie);
		client.post(url, as, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				Toast.makeText(Wo_ziliaoActivity.this, "修改成功", 0).show();
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				Toast.makeText(Wo_ziliaoActivity.this, "修改失败", 1).show();

			}
		});
		finish();
		
	}
	public void cancel(View v){
		finish();
	}

	private void initData() {
		// 向服务器发送请求，查询数据
		httpUtils = new HttpUtils();
		String url = "http://" + MyApplication.getIP()
				+ ":8080/Jinnang/WoGuanzhu";
		RequestParams params = new RequestParams();
		params.addBodyParameter("key", "2");
		params.addBodyParameter("username", MyApplication.username);
		System.out.println("传递的username" + MyApplication.username);
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// 获取服务器端返回的数据结果
						String result = responseInfo.result;
						 Log.e("-------格瑞特-------", result);
						// shiyongGson框架进行json解析
						Gson gson = new Gson();
						Type typeOfT = new TypeToken<List<UserBean>>() {
						}.getType();
						List<UserBean> list1 = gson.fromJson(result, typeOfT);
						list.addAll(list1);

						editText2.setText(list.get(0).getUser_nickname());
						editText3.setText(list.get(0).getUser_gender());
						wo_jianjie.setText(list.get(0).getUser_profile());

						String url = "http://" + MyApplication.getIP()
								+ ":8080/Jinnang/img/"
								+ list.get(0).getUser_imgPath();
						wo_photo.setstyle("circle");
						wo_photo.setImageUrl(url);
						 Log.e("hua------安全卫士", list.toString());
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub

					}
				});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case 1:
			startPhotoZoom(uri);// 剪裁
			break;
		case 2:
			if (data != null) {
				Uri uri = data.getData();// 获取本地地址得到图片
				startPhotoZoom(uri);// 剪裁
			}
			
			
			break;
		case 3:
			// 上传
			dialog.dismiss();
			string = this.getExternalCacheDir() + "/" + filename;
			Bitmap bitmap1 = BitmapFactory.decodeFile(this
					.getExternalCacheDir() + "/" + filename);
			//
			Circleimage image2 = new Circleimage();
			wo_photo.setImageBitmap(image2.toRoundBitmap(bitmap1));
			// upload();
			uploadMethod();
			wo_photo.setstyle("circle");
			break;

		default:
			break;
		}
	}

	private void uploadMethod(/* RequestParams params, String uploadHost */) {
		String url5 = "http://" + MyApplication.getIP()
				+ ":8080/Jinnang/imageservlet"; // 服务器接收地址
		RequestParams params1 = new RequestParams();
		params1.addBodyParameter("msg", "上传图片");
		params1.addBodyParameter("username", MyApplication.username);
		params1.addBodyParameter("img1", new File(string));
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, url5, params1,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
					}
				});
	}

	// 弹框
	private void showDialog() {
		View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
				null);
		Button button = (Button) view.findViewById(R.id.wo_take_photo);
		Button button1 = (Button) view.findViewById(R.id.wo_select);
		Button button2 = (Button) view.findViewById(R.id.wo_quxiao);
		 dialog = new Dialog(this,
				R.style.transparentFrameWindowStyle);
		dialog.setContentView(view, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		Window window = dialog.getWindow();
		// 设置显示动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = getWindowManager().getDefaultDisplay().getHeight();
		// 以下这两句是为了保证按钮可以水平满屏
		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

		// 设置显示位置
		dialog.onWindowAttributesChanged(wl);
		// 设置点击外围解散
		dialog.setCanceledOnTouchOutside(true);

		dialog.show();

		// 拍照
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				System.out.println(filename);
				uri = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), filename));
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
						Environment.getExternalStorageDirectory(), filename)));
				Log.e("urits", uri.toString());
				startActivityForResult(intent, 1);

			}
		});

		// 图册获取
		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent, 2);

			}
		});
		// 取消按钮
		button2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
	}

	// 图像裁剪
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		intent.putExtra("output",
				Uri.fromFile(new File(this.getExternalCacheDir(), filename)));
		startActivityForResult(intent, 3);
	}
}
